#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/2/26 20:15
# @Author  : Seven
# @File    : CameraCalibration.py
# @Software: PyCharm
# function : 摄像机标定
import cv2
import numpy as np
import glob

# 设置寻找亚像素角点的参数，采用的停止准则是最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# 准备目标点，例如 (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6 * 7, 3), np.float32)
# 将世界坐标系建在标定板上，所有点的Z坐标全部为0，所以只需要赋值x和y
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)

# 用于存储所有图像中的对象点和图像点的数组。
objpoints = []  # 存储在现实世界空间的3d点
imgpoints = []  # 储存图像平面中的2d点。
images = glob.glob('image/*.jpg')
for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 获取XY坐标
    size = gray.shape[::-1]
    # 找到图像平面点坐标点
    ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
    # 如果找到，添加3D点，2D点
    if ret:
        objpoints.append(objp)
        # 增加角点的准确度
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        imgpoints.append(corners2)
        # 画出并显示角点
        img = cv2.drawChessboardCorners(img, (7, 6), corners2, ret)
        cv2.imshow('img', img)
        cv2.waitKey(500)
# 相机标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, size, None, None)
# 保存相机参数
np.savez('C.npz', mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)
print("ret:", ret)
print("内参数矩阵:\n", mtx)
print("畸变系数:\n", dist)
print("旋转向量:", rvecs)  # 外参数
print("平移向量:", tvecs)  # 外参数


